package com.rjyb.dyxz.service.Impl;

import com.rjyb.dyxz.dao.IUserDao;
import com.rjyb.dyxz.dao.Impl.UserDaoImpl;
import com.rjyb.dyxz.pojo.User;
import com.rjyb.dyxz.service.IUserService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class UserServiceImpl implements IUserService {
    @Override
    public void enroll(String drawImg,String password1, User user, HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String regEx2 = "^(?=.*[0-9])(?=.*[a-zA-Z])(?=.*[^a-zA-Z0-9])(.{8,16})$";
        Pattern Password_Pattern = Pattern.compile(regEx2);
        Matcher matcher = Password_Pattern.matcher(user.getUserPwd());
        if (DrawImg(drawImg,req,resp)) {
            if (matcher.matches()) {
                if (user.getUserPwd().equals(password1)) {
                    IUserDao userDao = new UserDaoImpl();
                    if (userDao.CheckForPlagiarism(user.getUserName())) {
                        if(userDao.phoneNumber(user.getPhone())){
                        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                        String time = format.format(System.currentTimeMillis());
                        user.setReqTime(time);
                        user.setLogTime(time);
                        userDao.enroll(user);
                        req.getRequestDispatcher("Sign_in_to_register/index2.jsp").forward(req, resp);
                        }else {
                            System.out.println("手机号已被注册");
                            req.getRequestDispatcher("Sign_in_to_register/phoneNumber.jsp").forward(req, resp);
                        }
                    } else {
                        System.out.println("已有该账号");
                        req.getRequestDispatcher("Sign_in_to_register/Check_for_plagiarism.jsp").forward(req, resp);
                    }
                } else {
                    System.out.println("两次密码不正确");
                    req.getRequestDispatcher("unanimous.jsp").forward(req, resp);
                }
            } else {
                System.out.println("密码格式错误");
                req.getRequestDispatcher("Password_format.jsp").forward(req, resp);
            }
        }
    }

    private boolean DrawImg(String drawImg, HttpServletRequest req, HttpServletResponse resp) {
        String srvCode = req.getSession().getAttribute("srvCode").toString();
        if(srvCode.equalsIgnoreCase(drawImg)){
            return true;
        }else {
            System.out.println("验证码错误");
        }
        return false;
    }

}
